package com.CoreryBlack.service.Impl;

import com.CoreryBlack.Mapper.EmpExprMapper;
import com.CoreryBlack.Mapper.EmpMapper;
import com.CoreryBlack.po.*;
import com.CoreryBlack.service.EmpService;
import com.CoreryBlack.util.JwtUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @Description EmpServiceImpl
 * @Author CoreryBlack
 * @Date 2024-09-20
 */
@Component
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpExprMapper empExprMapper;

    public PageBean list(EmpQueryParam empQueryParam) {
        //调用插件，开始分页
        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());
        //底层会进行分页查询
        Page page1 = empMapper.list(empQueryParam);

        return new PageBean(page1.getTotal(),page1.getResult());
    }

    public void save(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");

        empMapper.insert(emp);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(List<Integer> ids) {
        empMapper.deleteById(ids);
        empExprMapper.deleteByEmpids(ids);
    }

    @Override
    public Emp getById(Integer id) {
        return empMapper.getById(id);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);

        List<Integer> ids = Arrays.asList(emp.getId());
        empExprMapper.deleteByEmpids(ids);

        List<EmpExpr> exprList = emp.getExprList();
        if(exprList!=null && exprList.size()>0) {
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));

            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    public List<Emp> queryString() {
        return empMapper.findAll();
    }

    @Override
    public LoginInfo login(Emp emp) {
        Emp e = empMapper.getNameAndPassword(emp);

        if(e != null) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", e.getId());
            claims.put("username", e.getUsername());
            claims.put("name", e.getName());
            String jwt = JwtUtils.generateJwt(claims);
            LoginInfo loginInfo = new LoginInfo(e.getId(),e.getUsername(),e.getName(),jwt);
            return loginInfo;
        }
        return null;
    }


}
